package com.gx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gx.common.exception.CommonException;
import com.gx.dal.dataobj.SysUserDo;
import com.gx.dal.mapper.SysUserMapper;
import com.gx.dto.command.SysUserAddCmd;
import com.gx.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户信息表 服务实现类
 *
 * @author liu-pj
 * @since 2024-03-26 11:43
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDo> implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Integer save(SysUserAddCmd userAddCmd) {
        //判断账号和手机号是否存在
        Long count = this.baseMapper.findUserCount(userAddCmd.getAccount(), userAddCmd.getPhone(), null);
        if (count > 0) {
            throw new CommonException("登录名称或手机号:[{},{}]已存在", userAddCmd.getAccount(), userAddCmd.getPhone());
        }
        //如果存在 加密后 set密码 保存到库
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        SysUserDo sysUserDo = BeanUtil.copyProperties(userAddCmd, SysUserDo.class);
        sysUserDo.setPassword(bCryptPasswordEncoder.encode(userAddCmd.getPassword()));
        this.save(sysUserDo);
        return sysUserDo.getId();
    }
}
